﻿
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Quickly.Spa.Shared;

namespace Quickly.SpaProxy;

internal sealed class SpaProxyStartupFilter : IStartupFilter
{
    public SpaProxyStartupFilter(
        SpaProxyLaunchManager spaProxyLaunchManager,
        IHostApplicationLifetime hostLifetime,
        ILogger<SpaProxyStartupFilter> logger,
        IOptions<SpaDevelopmentServerOptions> options)
    {
        _spaProxyLaunchManager = spaProxyLaunchManager;
        _hostLifetime = hostLifetime;
        _logger = logger;
        _options = options;
    }

    public SpaProxyLaunchManager _spaProxyLaunchManager { get; }
    public IHostApplicationLifetime _hostLifetime { get; }
    public ILogger<SpaProxyStartupFilter> _logger { get; }
    private IOptions<SpaDevelopmentServerOptions> _options { get; }

    public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
    {
        _ = StartIfNotRunning();

        return builder =>
        {
            builder.UseMiddleware<SpaProxyMiddleware>();
            next(builder);
        };

        async Task StartIfNotRunning()
        {
            try
            {
                foreach (var server in _options.Value)
                {
                    if (!await _spaProxyLaunchManager.IsSpaProxyRunning(_hostLifetime.ApplicationStopping, server.Key))
                    {
                        _spaProxyLaunchManager.StartInBackground(_hostLifetime.ApplicationStopping, server.Key);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "There was an error trying to lanuch the SPA proxy");
            }
        }
    }
}
